using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Windows.Forms;

namespace Splino
{
    /// <summary>
    /// Sorts a column of list view items
    /// </summary>
    public class ListViewColumnSorter : IComparer
    {
        private int _columnToSort;
        /// <summary>
        /// Gets or sets the index of the column being sorted
        /// </summary>
        public int ColumnToSort
        {
            get { return _columnToSort; }
            set { _columnToSort = value; }
        }

        private SortOrder _sortOrder;
        /// <summary>
        /// Gets or sets how items in the column are sorted
        /// </summary>
        public SortOrder SortOrder
        {
            get { return _sortOrder; }
            set { _sortOrder = value; }
        }

        private CaseInsensitiveComparer _comparer;

        /// <summary>
        /// Constructor
        /// </summary>
        public ListViewColumnSorter()
        {
            _columnToSort = 0;
            _sortOrder = SortOrder.None;
            _comparer = new CaseInsensitiveComparer();
        }

        /// <summary>
        /// Compares to ListViewItems
        /// </summary>
        /// <param name="x">The first ListViewItem to compare</param>
        /// <param name="y">THe second ListViewItem to compare</param>
        /// <returns>A number representing the comparison results</returns>
        public int Compare(object x, object y)
        {
            ListViewItem listViewItemX = (ListViewItem)x;
            ListViewItem listViewItemY = (ListViewItem)y;

            int compareResult = _comparer.Compare(listViewItemX.SubItems[_columnToSort].Text,
                listViewItemY.SubItems[_columnToSort].Text);

            int returnResult;

            switch (_sortOrder)
            {
                case SortOrder.Ascending:
                    returnResult = compareResult;
                    break;
                case SortOrder.Descending:
                    returnResult = -compareResult;
                    break;
                default:
                    returnResult = 0;
                    break;
            }

            return returnResult;
        }
    }
}
